<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开票日期" prop="kprq">
        <el-date-picker clearable
          v-model="queryParams.kprq"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开票日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="购买方名称" prop="buyerName">
        <el-input
          v-model="queryParams.buyerName"
          placeholder="请输入购买方名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入总金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="税额" prop="taxAmount">
        <el-input
          v-model="queryParams.taxAmount"
          placeholder="请输入税额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售方名称" prop="sellerName">
        <el-input
          v-model="queryParams.sellerName"
          placeholder="请输入销售方名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开票人" prop="drawer">
        <el-input
          v-model="queryParams.drawer"
          placeholder="请输入开票人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-row>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gd:invoice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gd:invoice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gd:invoice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gd:invoice:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="invoiceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="发票票号" align="center" prop="number" v-if="true"/>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="开票日期" align="center" prop="kprq" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.kprq, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="" align="center" prop="checksum" />
      <el-table-column label="购买方名称" align="center" prop="buyerName" />
      <el-table-column label="销售方名称" align="center" prop="sellerName" />
      <el-table-column label="总金额" align="center" prop="amount" />
      <el-table-column label="价税合计" align="center" prop="totalAmountString" />
      <el-table-column label="价税合计" align="center" prop="totalAmount" />
      <el-table-column label="开票人" align="center" prop="drawer" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gd:invoice:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gd:invoice:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改发票对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="请上传发票" prop="fj">
              <el-upload
                ref="upload"
                class="upload-demo"
                :action="src"
                name="files"
                :on-success="handleSuccess"
                :on-error="handleError"
                :before-remove="handleRemove"
                :headers="uploadHeaders"
                accept=".pdf"
                multiple
                :file-list="fjList"
                :on-preview="handlePreview"
              >
                <el-button size="small" type="primary"> <i class="el-icon-upload"></i> 点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传Excel文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="jiexiFile">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInvoice, getInvoice, delInvoice, addInvoice, updateInvoice, jxFj } from "@/api/gd/invoice";
import { getToken } from '@/utils/auth'
import { delFj } from '@/api/gd/fj'
import axios from 'axios'

export default {
  name: "Invoice",
  data() {
    return {
      // 附件上传 开始
      src: this.uploadSrc + '/gd/fj/file/batchUpload',
      uploadHeaders: { 'Authorization': 'Bearer ' + getToken() }, // 如果需要CSRF保护的话
      fjList: [],
      // 附件上传 结束
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发票表格数据
      invoiceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        machineNumber: undefined,
        code: undefined,
        kprq: undefined,
        checksum: undefined,
        buyerName: undefined,
        buyerCode: undefined,
        buyerAddress: undefined,
        buyerAccount: undefined,
        password: undefined,
        amount: undefined,
        taxAmount: undefined,
        totalAmountString: undefined,
        totalAmount: undefined,
        sellerName: undefined,
        sellerCode: undefined,
        sellerAddress: undefined,
        sellerAccount: undefined,
        payee: undefined,
        reviewer: undefined,
        drawer: undefined,
        type: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // ======  上传开始  ======
    handleSuccess(response, file, fileList) {
      if (response !== null && response !== undefined) {
        // 获取当前的上传的附件id
        let fileIds = []
        fileList.forEach(item => {
          if (item.response !== undefined) {
            fileIds.push(item.response[0].fj)
          }
        })
        // 更新状态或者通知用户上传成功
        this.$message.success('上传成功');
        // 上传成功以后，将id设置
        this.form.fj = fileIds.toString()
      }
    },
    // 上传失败回调
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.fjList = []
    },
    // 删除回调
    handleRemove(file, fileList) {
      // 调用删除附件功能，将附件进行删除
      let fjId = []
      let id = file.id || file.response[0].fj
      fjId.push(id)
      delFj(fjId).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功！")
        }
      })
    },
    // 文件点击回调
    async handlePreview(file) {
      let id = file.id || file.response[0].fj
      const response = await axios.get(this.uploadSrc + `/gd/fj/download/` + id, { responseType: 'blob', headers: this.uploadHeaders });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url
      link.download = file.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // ======  上传结束  ====
    /** 查询发票列表 */
    getList() {
      this.loading = true;
      listInvoice(this.queryParams).then(response => {
        this.invoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        number: undefined,
        title: undefined,
        machineNumber: undefined,
        code: undefined,
        kprq: undefined,
        checksum: undefined,
        buyerName: undefined,
        buyerCode: undefined,
        buyerAddress: undefined,
        buyerAccount: undefined,
        password: undefined,
        amount: undefined,
        taxAmount: undefined,
        totalAmountString: undefined,
        totalAmount: undefined,
        sellerName: undefined,
        sellerCode: undefined,
        sellerAddress: undefined,
        sellerAccount: undefined,
        payee: undefined,
        reviewer: undefined,
        drawer: undefined,
        type: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.number)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发票";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const number = row.number || this.ids
      getInvoice(number).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改发票";
      });
    },
    jiexiFile() {
      console.log("this.form", this.form)
      if (this.form.fj !== '' && this.form.fj !== null && this.form.fj !== undefined) {
        jxFj(this.form.fj).then(res => {
          if (res.code === 200) {
            this.$message.success("解析成功！")
          }
        })
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.fjList.length > 0) {
            this.buttonLoading = true;
            if (this.form.number != null) {
              updateInvoice(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addInvoice(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }else {
            this.$message.error("请先上传附件！")
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const numbers = row.number || this.ids;
      this.$modal.confirm('是否确认删除发票编号为"' + numbers + '"的数据项？').then(() => {
        this.loading = true;
        return delInvoice(numbers);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gd/invoice/export', {
        ...this.queryParams
      }, `invoice_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
